package com.example.listdetail;


import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ListView;
import android.widget.TextView;


import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.text.HtmlCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


public class NewContentFragment extends Fragment {
    private  WebView articleWebView;
    private String picName = "networkPic.jpg";
    private  View view;
    private   Fragment fragment;
    private  FragmentManager fm;
    private ArrayList<ListData> datas=new ArrayList<>();
    private ArrayList<Map<String, Object>> data2=new ArrayList<>();
    private ListView list_news;
    private  String id;

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    public void verifyPermission(Context context){
        int permission = ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    getActivity(),
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE);
        }

    }

    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == 22)
            {
                Log.d("len2", String.valueOf(datas.size()));
                MyAdapter myAdapter = new MyAdapter(datas, getActivity());
                list_news.setAdapter(myAdapter);

            }
        }
    };

    NewContentFragment() {

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fm=getActivity().getSupportFragmentManager();
         fragment=fm.findFragmentById(R.id.fragment_container);


        if(fragment==null){
            fragment=new RepliesFragment();
            fm.beginTransaction()
                    .add(R.id.fragment_container,fragment)
                    .commit();

        }
        id=getArguments().getString("id");
        Log.d("arc_id", id);
        okHttpGetDetail(id);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
         view = inflater.inflate(R.layout.fg_content, container, false);
        TextView txt_title = (TextView) view.findViewById(R.id.content_title);
        TextView txt_tab = (TextView) view.findViewById(R.id.content_tab);
        TextView txt_visit = (TextView) view.findViewById(R.id.content_visit);
        TextView txt_content=(TextView) view.findViewById(R.id.content_detail);
     //    articleWebView = (WebView) view.findViewById(R.id.webview);
        //getArgument获取传递过来的Bundle对象
        txt_title.setText(getArguments().getString("title"));
        txt_tab.setText(getArguments().getString("tab"));
        txt_visit.setText(getArguments().getString("visit_count"));
        String content=getArguments().getString("content");

        this.verifyPermission(getContext());
        URLImageParser p = new URLImageParser(txt_content, getActivity());
         Spanned htmlSpan = Html.fromHtml(getArguments().getString("content"), p, null);
         txt_content.setText(htmlSpan);
        return view;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        fm.beginTransaction().remove(fragment).commit();
    }

    public  void setContent(String content) {
        StringBuffer sb = new StringBuffer();

        //添加html

        sb.append("<html><head><meta http-equiv='content-type' content='text/html; charset=utf-8'>");
        sb.append("<meta charset='utf-8'  content='1'></head><body style='color: black'><p></p>");
        sb.append(content);
        sb.append("</body></html>");
        Log.d("666", sb.toString());
        // html字符串内容
        articleWebView.loadDataWithBaseURL("",sb.toString(),"text/html","UTF-8","");

    }
    //实现登录
    public void okHttpGetDetail(String id){
        HttpUtil.getDetail( new Callback() {
            public void onFailure(Call call, IOException e) {
                //在这里对异常情况进行处理
                //e.printStackTrace();
                Log.d("data:", "异常");
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //得到服务器返回的具体内容
                final String responseData = response.body().string();
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d("data:", responseData);
//                         ArrayList<Data> datas=new ArrayList<>();
                        try {
                            JSONObject jsonObject=new JSONObject(responseData);
                            JSONObject dataObject=jsonObject.getJSONObject("data");
                           // Log.d("success", dataObject.getString("success"));
                            JSONArray array=dataObject.getJSONArray("replies");
                            Log.d("lenxx", String.valueOf(array.length()));
                            for(int i=0;i<array.length();i++){
                                JSONObject obj=(JSONObject) array.get(i);
                                Log.d("objItem" ,obj.toString());
                                Map<String, Object> listItem =Replies.Instance(obj);
                                data2.add(listItem);

                                // 通过handler来发送消息，通知主线程去更新UI
                                handler.sendMessage(handler.obtainMessage(33, listItem));
                            }
                            EventBus.getDefault().post(
                                    new AnyEventType("data",data2));

                        }catch (Exception e){
                            e.printStackTrace();
                        }

                    }
                });
            }
        },id);
    }




}